//
//  DetailSingerViewController.m
//  LastTemp
//
//  Created by dllo on 15/4/24.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "DetailSingerViewController.h"
#import "SingerView.h"
#import "Cell01.h"
#import "Cell02.h"
#import "Cell03.h"
#import "InformationModel.h"
#import "AlbumModel.h"
#import "AlbumDetailModel.h"
#import "SingleModel.h"
#import "NetWorkingTool.h"
#import "UIImageView+WebCache.h"
#import "AVSingleton.h"
#import "AlbumDetailViewController.h"
#import "MJRefresh.h"
#import "bofangViewController.h"
#import "BassModel.h"
#import "NSNull+NullCast.h"
@interface DetailSingerViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView1;
@property(nonatomic, retain)UITableView *tableView2;
@property(nonatomic, retain)UITableView *tableView3;
@property(nonatomic, retain)UISegmentedControl *seg;
@property(nonatomic, retain)NSMutableArray *arr1;
@property(nonatomic, retain)NSMutableArray *arr2;
@property(nonatomic, retain)NSMutableArray *arr3;
@property(nonatomic, copy)NSNumber *count;
@property(nonatomic, assign)int page1;
@property(nonatomic, assign)int page2;
@property(nonatomic, retain)NSMutableArray *passPlayArr;
@property(nonatomic, retain)UIActivityIndicatorView *activity;
@end

@implementation DetailSingerViewController
- (void)dealloc
{
    [_arr1 release];
    [_arr2 release];
    [_arr3 release];
    [_seg release];
    [_tableView1 release];
    [_tableView2 release];
    [_tableView3 release];
    [_count release];
    [_count release];
    [_passPlayArr release];
    [_activity release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr1 = [NSMutableArray array];
        self.arr2 = [NSMutableArray array];
        self.arr3 = [NSMutableArray array];
        self.passPlayArr = [NSMutableArray array];
        self.page1 = 1;
        self.page2 = 1;
        self.title = @"歌手";
    }
    return self;
}

// 解析数据
- (void)Data1{
    [self.activity startAnimating];
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%@/songs?page=1&size=50", self.passSingerID];
    [NetWorkingTool netWorkingToolStr:str block:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *arr = [NSMutableArray array];
        arr = dic[@"data"];
        self.count = dic[@"pageCount"];
        for (NSInteger i = 0; i < arr.count; i++) {
            SingleModel *single = [[SingleModel alloc] init];
            [single setValuesForKeysWithDictionary:arr[i]];
            NSMutableArray *arrNew = [NSMutableArray array];
            arrNew = arr[i][@"urlList"];
            single.url = [arrNew firstObject][@"url"];
            [self.arr1 addObject:single];
            [single release];
        }
        [self.tableView1 reloadData];
        [self.activity stopAnimating];
    }];
}
- (void)Data2{
    [self.activity startAnimating];
     NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%@/albums?page=1", self.passSingerID];
    [NetWorkingTool netWorkingToolStr:str block:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *arr = [NSMutableArray array];
        arr = dic[@"data"];
        self.count = dic[@"pageCount"];
        NSLog(@"aaaaaa%@", self.count);
        for (NSInteger i = 0; i < arr.count; i++) {
            AlbumModel *album = [[AlbumModel alloc] init];
            [album setValuesForKeysWithDictionary:arr[i]];
            [self.arr2 addObject:album];
            [album release];
        }
        [self.tableView2 reloadData];
        [self.activity stopAnimating];
    }];
}
- (void)Data3{
    [self.activity startAnimating];
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%@?detail=true", self.passSingerID];
    [NetWorkingTool netWorkingToolStr:str block:^(id result) {
        NSMutableDictionary *dic = result;
        InformationModel *information = [[InformationModel alloc] init];
        [information setValuesForKeysWithDictionary:dic[@"data"]];
        [self.arr3 addObject:information];
        [self.tableView3 reloadData];
    }];
    [self.activity stopAnimating];
}
// 加载数据
- (void)reloadNewData1{
//    static int page = 1;
    ++self.page1;
//    NSLog(@"%d", page);
    NSNumber *num = [NSNumber numberWithInt:self.page1];
    if (num <= self.count) {
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%@/songs?page=%d&size=50", self.passSingerID, self.page1];
    [NetWorkingTool netWorkingToolStr:str block:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *arr = [NSMutableArray array];
        arr = dic[@"data"];
        for (NSInteger i = 0; i < arr.count; i++) {
            SingleModel *single = [[SingleModel alloc] init];
            [single setValuesForKeysWithDictionary:arr[i]];
            NSMutableArray *arrNew = [NSMutableArray array];
            arrNew = arr[i][@"urlList"];
            single.url = [arrNew firstObject][@"url"];
            [self.arr1 addObject:single];
            [single release];
        }
        [self.tableView1 reloadData];
    }];
}
    [self.tableView1 footerEndRefreshing];
}

- (void)reloadNewData2{
//    static int page = 1;
    ++self.page2;
//    NSLog(@"ssssssss%d", page);
    NSNumber *num = [NSNumber numberWithInt:self.page2];
    if (num <= self.count) {
        
        NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%@/albums?page=%d", self.passSingerID, self.page2];
        [NetWorkingTool netWorkingToolStr:str block:^(id result) {
            NSMutableDictionary *dic = result;
            NSMutableArray *arr = [NSMutableArray array];
            arr = dic[@"data"];
            for (NSInteger i = 0; i < arr.count; i++) {
                AlbumModel *album = [[AlbumModel alloc] init];
                [album setValuesForKeysWithDictionary:arr[i]];
                [self.arr2 addObject:album];
                [album release];
            }
            [self.tableView2 reloadData];
        }];
    }
    [self.tableView2 footerEndRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"39"]];

//    [self Data1];
    [self Data2];
    [self Data3];
    
    // 顶部View
    SingerView *singerView = [[SingerView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 150)];
    singerView.layer.cornerRadius = 10;
    [self.view addSubview:singerView];
    singerView.singerNameLabel.text = self.passSinger_name;
    NSURL *url = [NSURL URLWithString:self.passPic_url];
    [singerView.picImageView sd_setImageWithURL:url];
    [singerView release];
    
    // 接下来铺UISegmentedControl
//    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"单曲", @"专辑", @"简介"]];
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"专辑", @"简介"]];
    
    self.seg.frame = CGRectMake(0, 215, self.view.frame.size.width, 40);
    [self.view addSubview:self.seg];
    [self.seg addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
    self.seg.selectedSegmentIndex = 0;
    [_seg release];
    
    // 三个tableView三个自定义cell
//    self.tableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 255, self.view.frame.size.width, self.view.frame.size.height - 255 - 49) style:UITableViewStylePlain];
//    self.tableView1.tag = 1001;
////    self.tableView1.backgroundColor = [UIColor clearColor];
//    [self.view addSubview:self.tableView1];
    
//    self.tableView1.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"39"]];
//    
//    self.tableView1.delegate = self;
//    self.tableView1.dataSource = self;
//    [_tableView1 release];
    
    self.tableView2 = [[UITableView alloc] initWithFrame:CGRectMake(0, 255, self.view.frame.size.width, self.view.frame.size.height - 255 - 49) style:UITableViewStylePlain];
    self.tableView2.tag = 1002;
//    self.tableView2.backgroundColor = [UIColor clearColor];
//    self.tableView2.backgroundColor = [UIColor colorWithRed:185 / 255.0 green:221 / 255.0 blue:244 / 255.0 alpha:1];
    self.tableView2.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"9"]];
    [self.view addSubview:self.tableView2];
    
    self.tableView2.delegate = self;
    self.tableView2.dataSource = self;
    [_tableView2 release];
    
    self.tableView3 = [[UITableView alloc] initWithFrame:CGRectMake(0, 255, self.view.frame.size.width, self.view.frame.size.height - 255 - 49) style:UITableViewStylePlain];
    self.tableView3.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"9"]];
//    self.tableView3.backgroundColor = [UIColor clearColor];
    self.tableView3.tag = 1003;
    [self.view addSubview:self.tableView3];
    
    self.tableView3.delegate = self;
    self.tableView3.dataSource = self;
    [_tableView3 release];
    
 
//    [self.tableView1 addFooterWithCallback:^{
//        NSNumber *num1 = [NSNumber numberWithInt:1];
//        if (self.count > num1) {
//            [self reloadNewData1];
//        }
//    }];
//    
    [self.tableView2 addFooterWithCallback:^{
        NSNumber *num = [NSNumber numberWithInt:1];
        if (self.count > num) {
            [self reloadNewData2];
        }
    }];

    [self.view bringSubviewToFront:[self.view viewWithTag:1002]];
    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"03"] style:UIBarButtonItemStylePlain target:self action:@selector(rightClick:)];
//    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
    // 右button
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"player" style:UIBarButtonItemStylePlain target:self action:@selector(clickRightButton:)];
//    UIButton *RightButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    RightButton.frame = CGRectMake(0, 0, 64, 64);
//    [RightButton setBackgroundImage:[UIImage imageNamed:@"bb.gif"] forState:UIControlStateNormal];
//    //    [RightButton setBackgroundImage:[UIImage imageNamed:@"dd"] forState:UIControlStateNormal];
//    [RightButton addTarget:self action:@selector(clickRightButton:) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:RightButton] autorelease];
    
    
    // 进度轮
    self.activity = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [self.activity setCenter:CGPointMake(self.view.frame.size.width / 2, (self.view.frame.size.height - 113) / 2)]; // 指定进度轮中心点
    [self.activity setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:self.activity];
    [self.activity startAnimating];
    [_activity release];
}
#pragma mark 右button点击方法
- (void)clickRightButton:(UIBarButtonItem *)button{
    bofangViewController *playVC = [[bofangViewController alloc] init];
    playVC.allArr = [AVSingleton shareSingleton].fromArr;
    [self presentViewController:playVC animated:YES completion:^{
    }];
    [playVC release];
}
//#pragma mark 右button点击方法
//- (void)clickRightButton:(UIBarButtonItem *)button{
//    bofangViewController *playVC = [[bofangViewController alloc] init];
//    playVC.allArr = [AVSingleton shareSingleton].fromArr;
//    [self presentViewController:playVC animated:YES completion:^{
//    }];
//    [playVC release];
//}
// 编写按钮实现方法
//- (void)rightClick:(id)sender{
//    
//}
// 添加这个功能之后就可以出现滑动删除等功能
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//
//}

#pragma mark 重写系统按钮触发的方法
//- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
//    // 只要遇到重写父类的方法的时候, 就必须调用父类的方法, 因为子类的重写之后优先使用子类的方法, 父类会认为子类方法已经实现, 所以就要再去调用父类的方法
//    [super setEditing:editing animated:animated];
//    [self.tableView1 setEditing:editing animated:animated];
//}
////======================================================================================================
//- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    if (tableView == self.tableView1) {
//        UITableViewRowAction *collectAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"收藏" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
//            
//        }];
//        
//        UITableViewRowAction *shareAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"分享" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
//            
//        }];
//        return @[collectAction, shareAction] ;
//    }else{
//        return nil;
//    }
//}
//=======================================================================================================

// seg点击方法
- (void)click:(UISegmentedControl *)seg{
    switch (seg.selectedSegmentIndex) {
//        case 0:
//            [self.view bringSubviewToFront:[self.view viewWithTag:1001]];
//            break;
        case 0:
            [self.view bringSubviewToFront:[self.view viewWithTag:1002]];
            break;
        case 1:
            [self.view bringSubviewToFront:[self.view viewWithTag:1003]];
            break;
        default:
            break;
    }
}
// 协议必须实现的方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if ([tableView isEqual:self.tableView1]) {
//        return self.arr1.count;
//    }
    if ([tableView isEqual:self.tableView2]){
        return self.arr2.count;
    }else{
        return self.arr3.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if ([tableView isEqual:self.tableView1]) {
//        static NSString *reuse = @"reuse";
//        Cell01 *cell = [self.tableView1 dequeueReusableCellWithIdentifier:reuse];
//        if (!cell) {
//            cell = [[[Cell01 alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
//        }
//        cell.backgroundColor = [UIColor clearColor];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        SingleModel *single = self.arr1[indexPath.row];
//        cell.nameLabel.text = [NSString stringWithFormat:@"No.%ld %@", indexPath.row + 1,single.name];
//        cell.singerNameLabel.text = single.singerName;
//        cell.detailImageView.image = [UIImage imageNamed:@"02"];
//        return cell;
//    }
    if ([tableView isEqual:self.tableView2]){
        static NSString *reuse1 = @"reuse1";
        Cell02 *cell1 = [self.tableView2 dequeueReusableCellWithIdentifier:reuse1];
        if (!cell1) {
            cell1 = [[[Cell02 alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse1] autorelease];
        }
        cell1.backgroundColor = [UIColor clearColor];
        cell1.selectionStyle = UITableViewCellSelectionStyleNone;
        AlbumModel *album = self.arr2[indexPath.row];
        cell1.albumNameLabel.text = album.name;
        cell1.timeLabel.text = album.publishDate;
        NSURL *url = [NSURL URLWithString:album.picUrl];
        [cell1.picImageView sd_setImageWithURL:url];
        return cell1;
    }else if ([tableView isEqual:self.tableView3]){
        static NSString *reuse2 = @"reuse2";
        Cell03 *cell2 = [self.tableView3 dequeueReusableCellWithIdentifier:reuse2];
        if (!cell2) {
            cell2 = [[[Cell03 alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse2] autorelease];
        }
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
        cell2.backgroundColor = [UIColor clearColor];
        cell2.briefLabel.text = @"歌手简介";
        InformationModel *information = self.arr3[indexPath.row];
        cell2.brief.text = information.brief;
        cell2.awardsLabel.text = @"获奖记录";
        cell2.awards.text = information.awards;
        
        return cell2;
    }else{
        UITableViewCell *cell3 = [[UITableViewCell alloc] init];
        cell3.backgroundColor = [UIColor clearColor];
        return cell3;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if ([tableView isEqual:self.tableView1]) {
//        return 120;
//    }
    if ([tableView isEqual:self.tableView2]){
        return 120;
    }else{
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16],NSFontAttributeName, nil];
        InformationModel *information = self.arr3[indexPath.row];
        CGRect rect = [information.brief boundingRectWithSize:CGSizeMake(375, 400) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        
        NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:16],NSFontAttributeName, nil];
        CGRect rect1 = [information.awards boundingRectWithSize:CGSizeMake(375, 400) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic1 context:nil];
        
        return 100 + rect.size.height + rect1.size.height;
    }
}
// 点击实现功能
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.tableView1]) {
        SingleModel *single = self.arr1[indexPath.row];
        if ([AVSingleton shareSingleton].fromNum != indexPath.row || [AVSingleton shareSingleton].fromNum != 0) {
            [[AFSoundManager sharedManager] stop];
        }
        [[AFSoundManager sharedManager] startStreamingRemoteAudioFromURL:single.url andBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
            [AVSingleton shareSingleton].percentage = percentage;
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"mm:ss"];
            NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSince1970:elapsedTime];
            [AVSingleton shareSingleton].beginTime = [formatter stringFromDate:elapsedTimeDate];
            
            NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSince1970:timeRemaining];
            [AVSingleton shareSingleton].time = [formatter stringFromDate:timeRemainingDate];
            
            
        }];

        for (NSInteger i = 0; i < self.arr1.count; i++) {
            SingleModel *single1 = self.arr1[i];
            BassModel *baseModel = [[BassModel alloc] init];
            baseModel.name1 = single1.name;
            baseModel.singerName1 = single1.singerName;
            baseModel.url1 = single1.url;
            [self.passPlayArr addObject:baseModel];
            [baseModel release];
        }
        [AVSingleton shareSingleton].fromNum = indexPath.row;
        [AVSingleton shareSingleton].fromArr = self.passPlayArr;
        [AVSingleton shareSingleton].myBool = YES;
        bofangViewController *play = [[bofangViewController alloc] init];
        [self presentViewController:play animated:YES completion:^{
            
        }];
        
        
        
        
        
    }else if ([tableView isEqual:self.tableView2]){
        AlbumDetailViewController *albumDVC = [[AlbumDetailViewController alloc] init];
        albumDVC.passAlbum_name = [self.arr2[indexPath.row] name];
        albumDVC.passAlbumID = [self.arr2[indexPath.row] albumId];
        albumDVC.passPic_url = [self.arr2[indexPath.row] picUrl];
        [self.navigationController pushViewController:albumDVC animated:YES];
        [albumDVC release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
